package org.neptune.service.rabbit;

import java.util.Map;

import org.neptune.common.constant.NeptuneConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.collect.Maps;

/**
 * @author lwl
 * @date 2019/8/7 14:40
 */
@Configuration
public class SeckillQueueConfig {

	@Bean(name = "seckillQueue")
	public Queue seckillQueue() {
		return new Queue(NeptuneConstant.SECKILL_QUENE_NAME);
	}

	@Bean(name = "seckillLogQueue")
	public Queue seckillLogQueue() {
		// 创建秒杀日志队列
		return new Queue(NeptuneConstant.LOG_QUEUE_NAME);
	}

	@Bean(name = "seckillJsonLogQueue")
	public Queue seckillJsonLogQueue() {
		// 创建秒杀日志队列 json
		return new Queue(NeptuneConstant.LOG_JSON_QUENE_NAME);
	}

	@Bean(name = "homeCommentQueue")
	public Queue homeCommentQueue() {
		// 首页评论
		return new Queue(NeptuneConstant.HOME_COMMENT_QUENE_NAME);
	}

	/**
	 * 声明延迟队列交换机
	 * 
	 * @return DirectExchange
	 */
	@Bean
	public DirectExchange seckillDelayExchange() {
		return new DirectExchange(NeptuneConstant.SECKILL_EXCHANGE_NAME);
	}

	/**
	 * 声明延迟队列
	 * 
	 * @return Queue
	 */
	@Bean
	public Queue seckillDelayQueue() {
		return new Queue(NeptuneConstant.SECKILL_DELAY_QUEUE_NAME);
	}

	/**
	 * 绑定延迟队列到死信交换机
	 * 
	 * @return Binding
	 */
	@Bean
	public Binding bindingDelay() {
		return BindingBuilder.bind(seckillDlxQueue())
				.to(seckillDlxExchange())
				.with(NeptuneConstant.SECKILL_DELAY_QUEUE_ROUTE_KEY);
	}

	/**
	 * 声明死信队列交换机
	 *
	 * @return DirectExchange
	 */
	@Bean
	public DirectExchange seckillDlxExchange() {
		return new DirectExchange(NeptuneConstant.SECKILL_EXCHANGE_NAME);
	}

	/**
	 * 声明死信队列
	 *
	 * @return Queue
	 */
	@Bean
	public Queue seckillDlxQueue() {
		Map<String, Object> arguments = Maps.newHashMap();
		// 绑定该队列到延迟交换机
		arguments.put("x-dead-letter-exchange", NeptuneConstant.SECKILL_DELAY_EXCHANGE_NAME);
		// 10秒
		arguments.put("x-message-ttl", 10000);
		arguments.put("x-dead-letter-routing-key", NeptuneConstant.SECKILL_DELAY_QUEUE_ROUTE_KEY);
		return new Queue(NeptuneConstant.SECKILL_DLXQUEUE_NAME, true, false, false, arguments);
	}

	/**
	 * 绑定死信队列到死信交换机
	 *
	 * @return Binding
	 */
	@Bean
	public Binding bindingDlx() {
		return BindingBuilder.bind(seckillDlxQueue())
				.to(seckillDlxExchange())
				.with(NeptuneConstant.SECKILL_DLXQUEUE_ROUTE_KEY);
	}

}
